import { baseUrl } from "@/config/index.js";
// let baseApi = "http://t.fantasy-lab.com";
// import { getToken } from "@/utils/getAuth";
// 默认配置（不可变）
const DEFAULT_OPTIONS = {
  method: "GET",
  data: {},
  headers: {},
  isToken: true,
  form: false,
  showLoading: true,
  responseType: "text",
  validateStatus: (status) => status === 200,
};

// 请求队列（用于loading控制）
let pendingRequests = 0;

// 显示加载中
const showLoading = () => {
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });
};

// 隐藏加载中
const hideLoading = () => {
  pendingRequests--;
  if (pendingRequests <= 0) {
    uni.hideLoading();
  }
};

// 请求拦截器
const requestInterceptor = (config) => {
  // 显示loading
  if (config.showLoading) {
    pendingRequests++;
    pendingRequests === 1 && showLoading();
  }

  // 处理请求头
  const headers = {
    "content-type": config.form
      ? "application/x-www-form-urlencoded"
      : "application/json",
    ...config.headers,
  };

  // 添加Token
  if (config.isToken) {
    const token = uni.getStorageSync("token");
    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }
  }

  return {
    ...config,
    headers,
  };
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { config, data, statusCode } = response;
  console.log("responseInterceptor", response);
  if (statusCode == 401) {
    // 401 未授权，重新登录
    uni.reLaunch({
      url: "/pages/login/login",
    });
    return data;
  } else if (statusCode !== 200) {
    console.log(111);
    return Promise.reject({
      code: statusCode,
      message: data?.msg || "请求失败",
      data: data,
    });
  }else{
    return data;
  }
};

// 核心请求方法
function request(userOptions) {
  // 合并配置（创建新对象）
  const config = {
    ...DEFAULT_OPTIONS,
    ...userOptions,
    headers: { ...DEFAULT_OPTIONS.headers, ...userOptions.headers },
  };

  // 执行请求拦截器
  const mergedConfig = requestInterceptor(config);

  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + mergedConfig.url,
      method: mergedConfig.method.toUpperCase(),
      data: mergedConfig.data,
      header: mergedConfig.headers,
      responseType: mergedConfig.responseType,
      success: (res) => {
        try {
          const processed = responseInterceptor({
            config: mergedConfig,
            data: res.data,
            statusCode: res.statusCode,
          });
          if (processed.statusCode == 200) {
            resolve(processed.data);
          } else {
            console.log(333, processed, res);
            if (config.url == "/api/User/Register") {
              resolve(res.data);
            }
            if (res.statusCode == 401) {
              uni.showToast({
                title: "登录过期，请重新登录",
                icon: "none",
              });
            } else {
              uni.showToast({
                title: processed.errors,
                icon: "none",
              });
            }
            // uni.showToast({
            //   title: processed.errors,
            //   icon: "none",
            // });
          }
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        reject({
          code: -1,
          message: "网络错误，请检查网络连接",
          data: err,
        });
      },
      complete: () => {
        mergedConfig.showLoading && hideLoading();
      },
    });
  }).catch((error) => {
    console.log(error);
    // 统一错误提示
    if (!mergedConfig.silent) {
      uni.showToast({
        title: error.message,
        icon: "none",
        duration: 2000,
      });
    }
    return Promise.reject(error);
  });
}

export default request;
